/*****************************************************************************
* Keppe Messenger (KMP) Keppe Project-Team User Messaging System
* Copyright (C) 2013-2014 Keppe Project-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include "frmUpdate.h"
#include "UpdateThread.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QEventLoop>
#include <QSettings>
#include <QTimer>
#include <QDebug>

UpdateThread::UpdateThread(QString versionType, QString thisVersion, QObject *parent) :
    QThread(parent), versionType(versionType), thisVersion(thisVersion)
{
}

void UpdateThread::run()
{
    while (true)
    {
        bool updateAvailable = checkUpdate();
        if (updateAvailable)
        {
            emit updateIsNowAvailable();
        }
        QEventLoop lp;
        QTimer::singleShot(3600000,&lp,SLOT(quit()));
        lp.exec();
    }
}

bool UpdateThread::isVersionNewer(QString oldVersion, QString newVersion)
{
    QString oVersion = oldVersion;
    QString nVersion = newVersion;
    oVersion = oVersion.replace("-",".");
    nVersion = nVersion.replace("-",".");
    QStringList oldVL = oVersion.split(".");
    QStringList newVL = nVersion.split(".");
    int maxlen = 0;
    int srtlen = 0;
    QString srtval;
    if (oldVL.length() > newVL.length())
    {
        maxlen = oldVL.length();
        srtlen = newVL.length();
        srtval = "old";
    }
    else
    {
        maxlen = newVL.length();
        srtlen = oldVL.length();
        srtval = "new";
    }
    int curlen = 0;
    bool updateA = false;
    bool updateI = false;
    while (curlen != maxlen)
    {
        int oV = 0;
        int nV = 0;
        if (curlen < srtlen)
        {
            oV = oldVL.at(curlen).toInt();
            nV = newVL.at(curlen).toInt();
        }
        else if (srtval == "new")
        {
            nV = newVL.at(curlen).toInt();
        }
        else if (srtval == "old")
        {
            oV = oldVL.at(curlen).toInt();
        }
        if (oV < nV)
        {
            updateI = true;
        }
        else if (nV < oV)
        {
            if (!updateI)
            {
                updateA = true;
            }
        }
        curlen++;
    }
    if (!updateA)
    {
        return updateI;
    }
    else
    {
        return false;
    }
}

void UpdateThread::disableUpdateNotification()
{
    QSettings settings("Keppe","Keppe Messenger");
    settings.beginGroup("Update");
    settings.setValue("UpdateNotification",false);
    settings.endGroup();
    this->terminate();
}

bool UpdateThread::checkUpdate()
{
    bool updateAvailable = false;
    QString newVersion;
    QString updatePath = UpdatePath;

    QNetworkAccessManager *http = new QNetworkAccessManager();
    QNetworkReply *treply = http->get(QNetworkRequest(QUrl(updatePath + "stable" + versionType)));
    QEventLoop loop;
    QTimer::singleShot(5000, &loop, SLOT(quit()));
    QObject::connect(treply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    newVersion = QString::fromUtf8(treply->readAll());
    newVersion = newVersion.remove("\n");
    newVersion = newVersion.remove("\r");
    newVersion = newVersion.trimmed();

    if (isVersionNewer(thisVersion,newVersion) && newVersion != "") {updateAvailable = true;}

    emit setNewVersion(newVersion);

    return updateAvailable;
}

void UpdateThread::emitUpdate()
{
    emit updateIsNowAvailable();
}
